<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/static/layui/css/layui.css?t=1" media="all">
  <title>文件资源管理器</title>
  <style>
    /* 整体背景和字体 */
    body {
      margin: 0;
      padding: 0;
      height: 100vh;
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      background-color: #f5f6fa;
    }

    #file-explorer {
      height: 100%;
      padding: 1.25rem;
      box-sizing: border-box;
      /* max-width: 75rem;.php */
      margin: 0 auto;
      /* 修改背景色，这里使用 #f8f9fa 作为示例，你可以根据需求调整 */
      background-color: #f8f9fa;
    }

    /* 操作按钮样式 */
    .action-button {
      margin-right: .625rem;
      padding: .5rem 1rem;
      cursor: pointer;
      background-color: #4CAF50;
      color: white;
      border: none;
      border-radius: .25rem;
      transition: background-color 0.3s ease;
    }

    .action-button:hover {
      background-color: #45a049;
    }

    /* 路径栏样式 */
    #path-bar {
      margin: 1.25rem 0;
      padding: .75rem;
      background-color: white;
      border-radius: .375rem;
      box-shadow: 0 .125rem .25rem rgba(0, 0, 0, 0.1);
    }

    /* 文件列表样式 */
    #file-list {
      list-style-type: none;
      padding: 0;
      display: flex;
      flex-wrap: wrap;
      gap: 1.5rem;
    }

    .file-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      padding: 1rem;
      border-radius: .5rem;
      background-color: white;
      box-shadow: 0 .125rem .25rem rgba(0, 0, 0, 0.1);
      transition: transform 0.2s ease, box-shadow 0.2s ease;
      /* 限制文件项的宽度 */
      min-width: 9.375rem;
      /* 增加最小宽度 */
      max-width: 9.375rem;
    }

    .file-item:hover {
      transform: translateY(-0.1875rem);
      box-shadow: 0 .25rem .5rem rgba(0, 0, 0, 0.15);
    }

    .folder {
      color: #2196F3;
    }

    .file-icon {
      font-size: 2rem;
      /* 调整图标大小 */
      margin-bottom: .5rem;
      display: flex;
      /* 使用 flex 布局 */
      justify-content: center;
      /* 水平居中 */
      align-items: center;
      /* 垂直居中 */
    }

    /* 右键菜单样式 */
    #context-menu-list {
      position: absolute;
      background: white;
      border: none;
      border-radius: .375rem;
      box-shadow: 0 .25rem .5rem rgba(0, 0, 0, 0.15);
      display: none;
      min-width: 7.5rem;
      z-index: 1000;
      /* 确保菜单显示在最上层 */
    }

    #context-menu-list ul {
      list-style-type: none;
      padding: .5rem 0;
      margin: 0;
    }

    #context-menu-list li {
      padding: .625rem 1rem;
      cursor: pointer;
      color: #333;
      transition: background-color 0.2s ease;
    }

    #context-menu-list li:hover {
      background-color: #f0f0f0;
    }

    /* 文件或目录名称样式 */
    .file-item span {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
      text-align: center;
    }

    /* 非文件区域右键菜单样式 */
    #context-menu-bg {
      position: absolute;
      background: white;
      border: none;
      border-radius: .375rem;
      box-shadow: 0 .25rem .5rem rgba(0, 0, 0, 0.15);
      display: none;
      min-width: 7.5rem;
      z-index: 1000;
    }

    #context-menu-bg ul {
      list-style-type: none;
      padding: .5rem 0;
      margin: 0;
    }

    #context-menu-bg li {
      padding: .625rem 1rem;
      cursor: pointer;
      color: #333;
      transition: background-color 0.2s ease;
    }

    #context-menu-bg li:hover {
      background-color: #f0f0f0;
    }
    #pagination {
      float: right; /* 右浮动 */
      margin-top: 1rem;
      padding: 1rem 0;
      clear: both; /* 清除浮动影响 */
    }
  </style>
</head>

<body>
  <div id="file-explorer">
    <div>
      <!-- 新增回到根目录按钮，用图标替换文字 -->
      <button class="action-button" id="root-button">
        <i class="layui-icon layui-icon-home"></i>
      </button>
      <button class="action-button" id="back-button">
        <i class="layui-icon layui-icon-left"></i>
      </button>
      <button class="action-button" id="forward-button">
        <i class="layui-icon layui-icon-right"></i>
      </button>
      <button class="action-button" id="new-folder-button">
        <i class="layui-icon layui-icon-add-1"></i>
      </button>
      <button class="action-button" id="upload-button">
        <i class="layui-icon layui-icon-upload-drag"></i>
      </button>
    </div>
    <!-- 路径栏用图标替换部分文字 -->
    <div id="path-bar">
      <i class="layui-icon layui-icon-location"></i>
      <span id="current-path"></span>
    </div>
    <div id="file-list"></div>
    <!-- 添加分页控件 -->
    <div id="pagination" class="layui-box layui-laypage layui-laypage-default"></div>
  </div>
  <!-- 右键菜单 -->
  <div id="context-menu-container">
    <ul id="context-menu-list">
      <li id="download-item">下载</li>
      <li id="open-item">打开</li> 
      <li id="share-item">分享</li>
      <li id="move-item">移动</li>
      <li id="rename-item">重命名</li>
      <li id="delete-item">删除</li>
    </ul>
  </div>
  <!-- 非文件区域右键菜单 -->
  <div id="context-menu-bg-container">
    <ul id="context-menu-bg">
      <li id="new-folder-bg">新建文件夹</li>
      <li id="refresh-bg">刷新</li>
      <li id="upload-bg">上传</li>
    </ul>
  </div>
  <script src="/static/layui/layui.js"></script>
  <script>
    layui.use(['jquery', 'layer'], function () {
      const $ = layui.jquery;
      const layer = layui.layer;
      const laypage = layui.laypage;
      // 添加分页相关变量
      let currentPage = 1;
      const pageSize = 15; // 每页显示数量
      let totalCount = 0;
      let totalPages = 0;
      const fileList = document.getElementById('file-list');
      const currentPathSpan = document.getElementById('current-path');
      const backButton = document.getElementById('back-button');
      const forwardButton = document.getElementById('forward-button');
      const newFolderButton = document.getElementById('new-folder-button');
      const uploadButton = document.getElementById('upload-button');
      const contextMenu = document.getElementById('context-menu-list');
      const shareItem = document.getElementById('share-item');
      const deleteItem = document.getElementById('delete-item');
      const rootButton = document.getElementById('root-button');
      const renameItem = document.getElementById('rename-item');
      // 添加移动菜单项
      const moveItem = document.getElementById('move-item');

      const contextMenuBg = document.getElementById('context-menu-bg');
      const newFolderBg = document.getElementById('new-folder-bg');
      const refreshBg = document.getElementById('refresh-bg');
      const uploadBg = document.getElementById('upload-bg');

      // 非文件区域右键事件
      document.getElementById('file-explorer').addEventListener('contextmenu', (e) => {
        // 检查是否点击在文件项上，如果是则不处理
        if (e.target.closest('.file-item')) {
          return;
        }
        e.preventDefault();
        contextMenu.style.display = 'none'; // 隐藏文件右键菜单
        contextMenuBg.style.display = 'block';
        contextMenuBg.style.left = e.pageX + 'px';
        contextMenuBg.style.top = e.pageY + 'px';
      });

      // 点击其他地方隐藏右键菜单
      document.addEventListener('click', (e) => {
        const isClickInsideMenu = e.target.closest('#context-menu-list') || e.target.closest('#context-menu-bg');
        if (!isClickInsideMenu) {
          contextMenu.style.display = 'none';
          contextMenuBg.style.display = 'none';
        }
      });

      // 新建文件夹功能
      newFolderBg.addEventListener('click', () => {
        contextMenuBg.style.display = 'none';
        newFolderButton.click();
      });

      // 刷新功能
      refreshBg.addEventListener('click', () => {
        contextMenuBg.style.display = 'none';
        loadFiles();
      });

      // 上传功能
      uploadBg.addEventListener('click', () => {
        contextMenuBg.style.display = 'none';
        uploadButton.click();
      });

      moveItem.addEventListener('click', () => {
        if (selectedItem) {
          const itemId = selectedItem.isDirectory ? selectedItem.dir_id : selectedItem.id;
          const itemType = selectedItem.isDirectory ? 'dir' : 'file';
          // 使用 layer 弹出选择目录窗口
          layer.open({
            type: 2, // 2 表示 iframe 层
            title: '选择目标文件夹',
            area: ['25rem', '37.5rem'], // 弹框大小
            content: `/upload/index/selectDir?type=${itemType}&id=${itemId}`,
            success: function (layero, index) {
              // 可以在这里添加弹框成功打开后的逻辑
            },
            end: function () {
              // 弹框关闭后重新加载文件列表
              loadFiles();
            }
          });
        }
        contextMenu.style.display = 'none';
      });
      // 从本地存储中读取目录状态
      let currentDirId = parseInt(localStorage.getItem('currentDirId')) || 0;
      let history = JSON.parse(localStorage.getItem('history')) || [currentDirId];
      let historyIndex = parseInt(localStorage.getItem('historyIndex')) || 0;
      let selectedItem = null;

      // 加载文件和目录
      function loadFiles() {
        $.ajax({
          url: `/upload/index/explorer?dir_id=${currentDirId}&page=${currentPage}&page_size=${pageSize}`,
          type: 'GET',
          dataType: 'json',
          success: function (response) {
            if (response.current_path) {
              currentPathSpan.textContent = response.current_path;
            }

            fileList.innerHTML = '';
            totalCount = response.data.total_count || 0;
            totalPages = Math.ceil(totalCount / pageSize);

            // 优先显示文件夹
            if (response.data && response.data.dirs) {
              response.data.dirs.forEach(dir => {
                const listItem = createListItem(dir, true);
                fileList.appendChild(listItem);
              });
            }

            // 然后显示文件
            if (response.data && response.data.files) {
              response.data.files.forEach(file => {
                const listItem = createListItem(file, false);
                fileList.appendChild(listItem);
              });
            }

            // 渲染分页
            renderPagination();

            backButton.disabled = historyIndex === 0;
            forwardButton.disabled = historyIndex === history.length - 1;

            localStorage.setItem('currentDirId', currentDirId);
            localStorage.setItem('history', JSON.stringify(history));
            localStorage.setItem('historyIndex', historyIndex);
          },
          error: function () {
            layer.msg('加载文件失败，请稍后重试');
          }
        });
      }

      // 添加分页渲染函数
      function renderPagination() {
        laypage.render({
          elem: 'pagination',
          count: totalCount,
          curr: currentPage,
          limit: pageSize,
          layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
          jump: function(obj, first) {
            if (!first) {
              currentPage = obj.curr;
              loadFiles();
            }
          }
        });
      }

      // 获取文件扩展名
      function getFileExtension(fileName) {
        const parts = fileName.split('.');
        return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';
      }

      // 根据扩展名获取图片路径
      function getFileImagePath(extension) {
        const imageMap = {
          'jpg': '/static/upload/images/jpg.svg',
          'png': '/static/upload/images/jpg-1.svg',
          'gif': '/static/upload/images/gif.svg',
          'pdf': '/static/upload/images/pdf.svg',
          'doc': '/static/upload/images/docx.svg',
          'docx': '/static/upload/images/docx.svg',
          'xls': '/static/upload/images/xls.svg',
          'xlsx': '/static/upload/images/excel.svg',
          'ppt': '/static/upload/images/ppt.svg',
          'pptx': '/static/upload/images/ppt.svg',
          'mp4': '/static/upload/images/mp4.svg',
          'mov': '/static/upload/images/mp4.svg',
          'txt': '/static/upload/images/txt.svg',
          // 可以根据需要添加更多扩展名和对应的图片路径
        };
        return imageMap[extension] || '/static/upload/images/default.svg';
      }

      // 创建列表项
      function createListItem(item, isDirectory) {
        const listItem = document.createElement('li');
        listItem.className = isDirectory ? 'file-item folder' : 'file-item';

        // 修改为使用 img 元素
        const icon = document.createElement('img');
        icon.className = 'file-icon';
        // 增大图标尺寸
        icon.style.width = '3rem';
        icon.style.height = '3rem';
        if (isDirectory) {
          // 使用文件夹图片
          icon.src = '/static/upload/images/folder.svg';
        } else {
          const extension = getFileExtension(item.file_name);
          const imagePath = getFileImagePath(extension);
          icon.src = imagePath;
        }
        listItem.appendChild(icon);

        const nameSpan = document.createElement('span');
        const fullName = isDirectory ? item.dir_name : item.file_name;
        if (fullName) {
          nameSpan.textContent = fullName;
          nameSpan.setAttribute('title', fullName);
        } else {
          nameSpan.textContent = fullName;
          nameSpan.setAttribute('title', nameSpan.textContent);
        }
        listItem.appendChild(nameSpan);

        // 右键点击事件
        listItem.addEventListener('contextmenu', (e) => {
          e.preventDefault(); // 确保阻止默认右键菜单
          e.stopPropagation(); // 阻止事件冒泡
          selectedItem = { ...item, isDirectory };
          // 隐藏非文件区域右键菜单
          contextMenuBg.style.display = 'none'; 
          contextMenu.style.display = 'block';
          contextMenu.style.left = e.pageX + 'px';
          contextMenu.style.top = e.pageY + 'px';

          const downloadItem = document.getElementById('download-item');
          const openItem = document.getElementById('open-item');
          // 判断是否为文件夹，若是则显示打开按钮，否则隐藏
          if (isDirectory) {
            downloadItem.style.display = 'none';
            openItem.style.display = 'block';
            shareItem.style.display = 'none';
          } else {
            downloadItem.style.display = 'block';
            openItem.style.display = 'none';
            shareItem.style.display = 'block';
          }
        });

        // 单击事件，用于选中项
        listItem.addEventListener('click', (e) => {
          e.stopPropagation();
          selectedItem = { ...item, isDirectory };
          // 可以添加选中样式，例如改变背景色
          const allItems = document.querySelectorAll('.file-item');
          allItems.forEach(item => {
            item.style.backgroundColor = 'white';
          });
          listItem.style.backgroundColor = '#e6f7ff';
        });
        
        // 双击事件
        listItem.addEventListener('dblclick', () => {
          if (isDirectory) {
            // 双击目录，打开目录
            history = history.slice(0, historyIndex + 1);
            history.push(item.dir_id);
            historyIndex++;
            currentDirId = item.dir_id;
            loadFiles();
          } else {
            // 双击文件，执行下载逻辑
            const itemId = item.id;
            // 判断是否是被iframe加载的页面
            if (window.self !== window.top) {
              // 是被iframe加载的页面，使用隐藏表单提交
              const form = document.createElement('form');
              form.method = 'GET';
              form.action = `/upload/index/download`;
              form.target = '_blank';
              form.style.display = 'none';

              const input = document.createElement('input');
              input.type = 'hidden';
              input.name = 'id';
              input.value = itemId;
              form.appendChild(input);

              window.parent.document.body.appendChild(form);
              form.submit();
              window.parent.document.body.removeChild(form);
            } else {
              // 不是被iframe加载的页面，直接使用window对象
              window.location.href = `/upload/index/download?id=${itemId}`;
            }
          }
        });

        return listItem;
      }

      // 点击页面其他地方隐藏右键菜单
      document.addEventListener('click', () => {
        contextMenu.style.display = 'none';
      });

      // 分享功能
      shareItem.addEventListener('click', () => {
        if (selectedItem && !selectedItem.isDirectory) {
          const itemId = selectedItem.id;
          $.ajax({
            url: `/upload/index/siteShare`,
            type: 'GET',
            data: { id: itemId },
            dataType: 'json',
            success: function (response) {
              if (response.code === 0) {
                layer.msg(response.msg);
              } else {
                layer.msg(response.msg);
              }
            },
            error: function () {
              layer.msg('分享失败，请稍后重试', { icon: 5 });
            }
          });
        }
        contextMenu.style.display = 'none';
      });

      // 下载功能
      const downloadItem = document.getElementById('download-item');

      // 下载功能
      downloadItem.addEventListener('click', () => {
        if (selectedItem && !selectedItem.isDirectory) {
          const itemId = selectedItem.id;
          // 判断是否是被iframe加载的页面
          if (window.self !== window.top) {
            // 是被iframe加载的页面，使用隐藏表单提交
            const form = document.createElement('form');
            form.method = 'GET';
            form.action = `/upload/index/download`;
            form.target = '_blank';
            form.style.display = 'none';

            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'id';
            input.value = itemId;
            form.appendChild(input);

            window.parent.document.body.appendChild(form);
            form.submit();
            window.parent.document.body.removeChild(form);
          } else {
            // 不是被iframe加载的页面，直接使用window对象
            window.location.href = `/upload/index/download?id=${itemId}`;
          }
          return;
        }
        contextMenu.style.display = 'none';
      });

      // 删除功能
      deleteItem.addEventListener('click', () => {
        if (selectedItem) {
          const itemName = selectedItem.isDirectory ? selectedItem.dir_name : selectedItem.file_name;
          layer.confirm(`确定要删除 ${itemName} 吗？`, {
            icon: 3,
            title: '确认删除'
          }, function (index) {
            const itemId = selectedItem.isDirectory ? selectedItem.dir_id : selectedItem.id;
            const itemType = selectedItem.isDirectory ? 'dir' : 'file';
            $.ajax({
              url: `/upload/index/deleteFile`,
              type: 'POST',
              data: {
                id: itemId,
                type: itemType
              },
              dataType: 'json',
              success: function (response) {
                if (response.code === 0) {
                  layer.msg('删除成功');
                  loadFiles();
                } else {
                  layer.msg(response.msg || '删除失败，未知错误');
                }
              },
              error: function () {
                layer.msg('删除失败，请稍后重试');
              }
            });
            contextMenu.style.display = 'none';
            layer.close(index);
          });
        }
      });

      // 后退功能
      backButton.addEventListener('click', () => {
        if (historyIndex > 0) {
          historyIndex--;
          currentDirId = history[historyIndex];
          loadFiles();
        }
      });

      // 前进功能
      forwardButton.addEventListener('click', () => {
        if (historyIndex < history.length - 1) {
          historyIndex++;
          currentDirId = history[historyIndex];
          loadFiles();
        }
      });

      // 回到根目录功能
      rootButton.addEventListener('click', () => {
        currentDirId = 0; // 设置为根目录 ID
        history = [0]; // 重置历史记录
        historyIndex = 0; // 重置历史索引
        loadFiles(); // 重新加载文件列表
      });

      // 新建文件夹功能
      newFolderButton.addEventListener('click', () => {
        layer.prompt({
          title: '请输入新文件夹的名称',
          formType: 0
        }, function (value, index) {
          if (value) {
            $.ajax({
              url: `/upload/index/createDir`,
              type: 'POST',
              data: {
                folder_name: value,
                parent_dir_id: currentDirId
              },
              dataType: 'json',
              success: function (response) {
                if (response.code === 0) {
                  layer.msg('文件夹创建成功');
                  loadFiles();
                } else {
                  layer.msg(response.msg);
                }
              },
              error: function () {
                layer.msg('创建文件夹失败，请稍后重试');
              }
            });
          }
          layer.close(index);
        });
      });

      // 重命名功能
      renameItem.addEventListener('click', () => {
        if (selectedItem) {
          const itemName = selectedItem.isDirectory ? selectedItem.dir_name : selectedItem.file_name;
          layer.prompt({
            title: `重命名 ${itemName}`,
            formType: 0,
            value: itemName
          }, function (newName, index) {
            if (newName) {
              const itemId = selectedItem.isDirectory ? selectedItem.dir_id : selectedItem.id;
              const itemType = selectedItem.isDirectory ? 'dir' : 'file';
              $.ajax({
                url: `/upload/index/renameItem`,
                type: 'POST',
                data: {
                  id: itemId,
                  type: itemType,
                  new_name: newName
                },
                dataType: 'json',
                success: function (response) {
                  if (response.code === 0) {
                    layer.msg('重命名成功');
                    loadFiles();
                  } else {
                    layer.msg(response.msg || '重命名失败，未知错误');
                  }
                },
                error: function () {
                  layer.msg('重命名失败，请稍后重试');
                }
              });
            }
            layer.close(index);
          });
          contextMenu.style.display = 'none';
        }
      });

      // 打开菜单项点击事件
      // Get the new open menu item
      const openItem = document.getElementById('open-item'); 
      
      if (openItem) {
        // Open menu item click event
        openItem.addEventListener('click', () => {
          if (selectedItem && selectedItem.isDirectory) {
            history = history.slice(0, historyIndex + 1);
            history.push(selectedItem.dir_id);
            historyIndex++;
            currentDirId = selectedItem.dir_id;
            loadFiles();
          }
          contextMenu.style.display = 'none';
        });
      } else {
        console.error('The open-item element was not found.');
      }

      // 上传按钮点击事件
      uploadButton.addEventListener('click', () => {
        const url = `/cloud/?dirId=${currentDirId}&hiddenHeader=1`;
        let uploadLayerIndex; // 定义一个变量来存储弹窗的索引
        layer.open({
          type: 2,
          title: '文件上传',
          shade: 0.3,
          hideOnClose: true,
          area: ['80%', '80%'],
          content: url,
          success: function (layero, index) {
            uploadLayerIndex = index; // 保存弹窗的索引
          },
          end: function () {
            // 关闭弹窗后刷新文件列表
            loadFiles();
          }
        });
      });

      // 初始化加载文件
      loadFiles();
    });
  </script>
</body>

</html>